import * as React from 'react';
import { useEffect, useState } from 'react';
import { Button, Card, Typography, Space, Layout } from 'antd';
import { useNavigate } from 'react-router-dom';

const { Title, Text } = Typography;
const { Content, Header } = Layout;

interface User {
  username: string;
  email: string;
}

const Home: React.FC = () => {
  const [user, setUser] = useState<User | null>(null);
  const navigate = useNavigate();

  useEffect(() => {
    // 检查用户是否已登录
    const token = localStorage.getItem('token');
    const userStr = localStorage.getItem('user');
    
    if (!token || !userStr) {
      // 如果未登录，重定向到登录页
      navigate('/login');
      return;
    }
    
    try {
      const userData = JSON.parse(userStr);
      setUser(userData);
    } catch (e) {
      // 如果解析出错，清除用户信息并重定向
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      navigate('/login');
    }
  }, [navigate]);

  const handleLogout = () => {
    // 清除用户登录信息
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    
    // 跳转到登录页面
    navigate('/login');
  };

  if (!user) {
    return null; // 如果未登录，不显示任何内容（会重定向到登录页）
  }

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Header style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '0 24px' }}>
        <Title level={3} style={{ color: 'white', margin: 0 }}>用户认证系统</Title>
        <Button type="primary" danger onClick={handleLogout}>
          退出登录
        </Button>
      </Header>
      
      <Content style={{ padding: '50px', display: 'flex', justifyContent: 'center' }}>
        <Card style={{ width: 500 }}>
          <Title level={2}>欢迎回来！</Title>
          
          <Space direction="vertical" size="large" style={{ width: '100%', marginTop: 30 }}>
            <div>
              <Text strong>用户名：</Text>
              <Text>{user.username}</Text>
            </div>
            
            <div>
              <Text strong>邮箱：</Text>
              <Text>{user.email}</Text>
            </div>
            
            <div style={{ marginTop: 30 }}>
              <Text type="secondary">
                您已成功登录到系统。这是一个简单的用户认证演示应用。
              </Text>
            </div>
          </Space>
        </Card>
      </Content>
    </Layout>
  );
};

export default Home; 